import globals
import time
import yaml
import threading
import copy

def wait_till_neighbors_reply (waitDest, user, returnMessageList) :

    #print 'In wait till neighbors reply : user [%s]' % (user)
    #cloneList = []
    #for i in waitDest :
    #    cloneList.append(i)

    items = len(waitDest)

    while items > 0  :

        if globals.globalShutdown == True :
            print "broken from loop"
            break

        #print "here",
        try :
            globals.globalWaitListLock.acquire()
            if (len(globals.globalWaitMessageList) > 0) :
                #cloneList = []
                #for item in  globalWaitMessageList :
                #    cloneList.append(item)
                cloneList = copy.deepcopy(globals.globalWaitMessageList)
                i = 0
                for item in cloneList :
                    '''
                    if item.mtype == "node_failure" :
                        print "broken from loop"
                        break
                    '''
                    #print item
                    if item.mtype.replace("set_message_for_", "") == user :
                        items = items - 1
                        femsgList = yaml.load(item.data)
                        if not femsgList == None :
                            returnMessageList.extend(femsgList)
                        globals.globalWaitMessageList.pop(i)
                    else :
                        i = i + 1
        finally :
            globals.globalWaitListLock.release()
    #print "Break Waiting"
    #print "in wait globalWaitMessageList is : "
    #print len(globalWaitMessageList)
    return returnMessageList


'''
    while items > 0 :

        try:
            while not globalWaitMessageQueue.empty() :

                #globalQueueLock.acquire()
                item =  globalWaitMessageQueue.get(False, None)
                #globalQueueLock.release()
                #print 'Message received in Wait messages is : '
                #time.sleep(1)
                #print item
                #waitDest.remove(item.src)
                items = items - 1
                femsgList = yaml.load(item.data)
                if not femsgList == None :
                    returnMessageList.extend(femsgList)


        except Queue.Empty :
            print "Queue is empty"
        except Queue.Full :
            print "Queue is full"
        except Exception :
            print "exception"
        finally:
            pass
    '''
